<template>
  <div class="color-picker diamond float-left" ref="colorContainer">
    <span class="input-group-addon color-picker-container">
      <span class="current-color" :style="'background-color: ' + value" @click="togglePicker()"></span>
      <chrome-picker :value="colors" @input="updateFromPicker" v-if="displayPicker" />
    </span>
  </div>
</template>

<script>
import { Chrome } from 'vue-color'

export default {
  name: 'UIColor',
  components: {
    'chrome-picker': Chrome
  },
  props: {
    'value': {
      default: '#333'
    }
  },
  data () {
    return {
      colors: {
        hex: '#000000'
      },
      colorValue: '',
      displayPicker: false
    }
  },
  mounted: function () {
    this.colorValue = this.value;
    this.setColor();
  },
  methods: {
    setColor () {
      this.updateColors(this.colorValue);
    },
    updateColors (color) {
      if (color.slice(0, 1) === '#') {
        this.colors = {
          hex: color
        };
      } else if (color.slice(0, 4) === 'rgba') {
        var rgba = color.replace(/^rgba?\(|\s+|\)$/g,'').split(','),
          hex = '#' + ((1 << 24) + (parseInt(rgba[0]) << 16) + (parseInt(rgba[1]) << 8) + parseInt(rgba[2])).toString(16).slice(1);
        this.colors = {
          hex: hex,
          a: rgba[3],
        }
      }
    },
    showPicker () {
      document.addEventListener('click', this.documentClick);
      this.displayPicker = true;
    },
    hidePicker () {
      document.removeEventListener('click', this.documentClick);
      this.displayPicker = false;
    },
    togglePicker () {
      this.displayPicker ? this.hidePicker() : this.showPicker();
    },
    updateFromPicker (color) {
      this.colors = color;
      if (color.rgba.a === 1) {
        this.colorValue = color.hex;
      } else {
        this.colorValue = 'rgba(' + color.rgba.r + ', ' + color.rgba.g + ', ' + color.rgba.b + ', ' + color.rgba.a + ')';
      }
    },
    documentClick (e) {
      var el = this.$refs.colorContainer, target = e.target;
      if (el !== target && !el.contains(target)) {
        this.hidePicker()
      }
    }
  },
  watch: {
    colorValue: function (val) {
      if (val) {
        this.updateColors(val);
        this.$emit('childChange', val);
      }
    }
  }
}
</script>

<style scoped>
  .vc-chrome {
    position: absolute;
    top: 35px;
    right: 0;
    z-index: 9;
  }
  .current-color {
    display: inline-block;
    width: 16px;
    height: 16px;
    background-color: #000;
    cursor: pointer;
  }
  .diamond {
    width: 20px;
  }
</style>
